<template>
  <div class="shopCar">
    <div class="tableList">
      <ul class="title">
        <li v-for="(item, index) in sortArr" :key="index">
          <span>{{ item.title }}</span>
          <strong>
            <i @click="checked(item.name[0])" :class="{ 'active': item.name[0] == sortActive }" class="top"></i>
            <i @click="checked(item.name[1])" :class="{ 'active': item.name[1] == sortActive }" class="bottom"></i>
          </strong>
        </li>
      </ul>
      <ul class="goodsInfo" ref="goodsBox">
        <li v-for="(item, index) in goodsArr" :key="index">
          <div class="goodsImg">
            <img @click="lookImg(item.picList ? JSON.parse(item.picList)[0] : noImg)" :src="item.picList ? JSON.parse(item.picList)[0] : noImg" alt="商品主图">
          </div>
            <div class="goodsDetail">
              <h6>{{ item.title }}</h6>
              <p :title="item.description">{{ item.description }}</p>
            </div>
            <div class="price">
              <span>单价：{{ item.price }}元</span>
              <br />
              <span>重量：
                <strong>{{ item.weight }}kg</strong>
              </span>
              <!-- <br />
            <span>销量：{{ item.salesNum }}件</span> -->
              <br />
              <span>库存：{{ item.stockNum }}件</span>
            </div>
            <div class="operate">
              <el-input-number size="small" :min="0" v-model="item.initNum"></el-input-number>
              <p class="text-button-b" @click="addPackage(item.initNum, item)">加入礼品包</p>
            </div>
        </li>
        <li class="loading" ref="loading" v-if="goodsDataObj.currPageNo < goodsDataObj.pageNos">
          <i class="el-icon-loading"></i>
        </li>
      </ul>
    </div>
    <div class="cars">
      <div class="titleInput">
        <h2>礼品包列表</h2>
      </div>
      <ul class="checkedList">
        <li v-if="checkedArr.length != 0" v-for="(item, index) in checkedArr" :key="index">
          <img :src="item.picList ? JSON.parse(item.picList)[0] : noImg" alt="img">
          <span>{{ item.weight }}kg</span>
          <span>{{ `￥`+ item.price }} * {{ item.num }}</span>
          <i class="el-icon-circle-close" @click="deleChecked(index)"></i>
        </li>
        <li class="noContent" v-if="checkedArr.length == 0">
          <img :src="noImg" alt="无数据">
        </li>
      </ul>
      <div class="totalPrice">
        <span>
          <i>套餐重量：</i>
          <strong>{{ totalObj.weightTotal }} kg</strong>
        </span>
        <br>
        <span>
          <i>商品金额：</i>
          <em>{{ totalObj.priceTotal }} 元</em>
        </span>
        <br>
        <span v-if="type==3">
          <i>运费：</i>
          <em>{{ logisticPrice }} 元</em>
        </span>
        <p class="total" v-if="type==3">
          <b>总计：</b>
          <strong>{{ ((logisticPrice - 0) + (totalObj.priceTotal - 0)).toFixed(2) }}</strong>
        </p>
        <!-- <br> -->
        <!-- <b>备注：陕西、甘肃、宁夏、新疆、西藏、内蒙 运费另计</b> -->
      </div>
      <div class="footer" v-if="type==1">
        <b class="button-n" @click="sureAddPackage">确定添加礼品包</b>
      </div>
      <div class="footer" v-if="type==2">
        <b class="button-n" @click="sureEditPackage">确定修改礼品包</b>
        <br />
        <i class="text-button-b" @click="closeCar">取消修改</i>
      </div>
      <div class="footer" v-if="type==3">
        <i class="text-button-b" @click="setCommonPackage">设为常用礼品包</i>
        <div class="btns">
          <b class="button-w" @click="toSamApplay">样品申请</b>
          <b class="button-n" @click="goWhere('ordersNow')">立即采购</b>
        </div>
      </div>
    </div>
  </div>
</template>
<script type="text/ecmascript-6">
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'shopCar',
  data () {
    return {
      noImg: require('../../../assets/images/noContainer.svg'),
      giftNameForm: {
        name: ''
      },
      giftNameRules: {
        name: [
          {
            required: true,
            message: '请输入礼品包标题',
            trigger: 'blur'
          }
        ]
      },
      sortActive: 'sales_num-desc',
      sortArr: [
        {
          title: '价格排序',
          value: 'price',
          name: ['price-asc', 'price-desc']
        },
        {
          title: '重量排序',
          value: 'weight',
          name: ['weight-asc', 'weight-desc']
        },
        {
          title: '销量排序',
          value: 'sales',
          name: ['sales_num-asc', 'sales_num-desc']
        }
      ],
      goodsDataObj: {},
      goodsArr: [], // 商品列表数组
      checkedArr: [], // 已选择商品列表
      pageNo: 1,
      pageSize: 10,
      dispareStoreArrGoodsIds: []
      // dispareStoreArrGoodsIds: ['GN201806015398274889', 'GN201809076715392338', 'GN201809086715395633', 'GN201809086715395652', 'GN201809086715395710', 'GN201809086715395722', 'GN201809126715432415']
    }
  },
  props: {
    type: { // 1 添加 / 2 编辑
      type: String
    },
    fixedArr: {
      type: Array
    }
  },
  computed: {
    logisticPrice () {
      let weight = this.totalObj.weightTotal
      let priceObj = this.logisticList
      let logisticMoney = 0
      if (weight > 0 && weight <= 0.5) {
        logisticMoney = priceObj.firstPrice
      } else if (weight > 0.5 && weight <= 1) {
        logisticMoney = priceObj.middlePrice
      } else if (weight > 1) {
        logisticMoney = (1 * priceObj.middlePrice + (Math.ceil(weight - 1)) * priceObj.endPrice)
      } else {
        logisticMoney = 0
      }
      return logisticMoney.toFixed(2)
    },
    totalObj: {
      get: function () {
        let priceTotal = 0
        let weightTotal = 0
        for (let i = 0; i < this.checkedArr.length; i++) {
          priceTotal += this.checkedArr[i].price * this.checkedArr[i].num
          weightTotal += this.checkedArr[i].weight * this.checkedArr[i].num
        }
        return {
          priceTotal: priceTotal.toFixed(2),
          weightTotal: weightTotal.toFixed(2)
        }
      },
      set: function (val) {
        return val
      }
    },
    ...mapGetters([
      'userInfo',
      'logisticList'
    ])
  },
  watch: {
    sortActive () {
      this.pageNo = 1
      this.$refs.goodsBox.scrollTop = 0
      this.getGoodsList()
    }
  },
  methods: {
    lookImg (url) {
      this.$lookImg.showSmall(url)
    },
    goWhere (router) {
      this.$router.push({ name: router })
    },
    isDifferent (productId) { // 是否分仓的商品
      let bol = false
      for (let i = 0; i < this.checkedArr.length; i++) {
        if (this.dispareStoreArrGoodsIds.indexOf(this.checkedArr[i].productId) < 0) { // 无特殊商品
          if (this.dispareStoreArrGoodsIds.indexOf(productId) >= 0) { // 选择的为特殊商品
            bol = true
            break
          }
        } else { // 有特殊商品
          if (this.dispareStoreArrGoodsIds.indexOf(productId) < 0) { // 选择的为正常商品
            bol = true
            break
          }
        }
      }
      return bol
    },
    toSamApplay () {
      this.sureAddPackage(999)
    },
    setCommonPackage () { // 设置为常用礼品包
      this.$emit('setCommonPackage', this.checkedArr)
    },
    closeCar () { // 关闭取消修改礼品包
      this.$emit('closeCar')
    },
    checked (activeName) { // 筛选条件的内容
      if (this.sortActive === activeName) {
        this.sortActive = 'sales_num-desc'
      } else {
        this.sortActive = activeName
      }
    },
    addPackage (initNum, item) { // 加入礼品包列表
      if (initNum <= 0) {
        this.$message({
          message: '请输入商品数量',
          type: 'warning'
        })
      } else {
        if ((this.totalObj.weightTotal - 0) + (item.weight * initNum - 0) > 20) {
          this.$message({
            message: '单个包裹重量上限为20KG',
            type: 'warning'
          })
        } else if (this.isDifferent(item.productId)) {
          this.$message({
            message: '手机周边的商品不能与其他商品混合购买哦',
            type: 'warning'
          })
        } else {
          let checked = this.checkedArr
          for (let i = 0; i < checked.length; i++) {
            if (checked[i].productId === item.productId) {
              checked[i].num += initNum
              return false
            }
          }
          this.checkedArr.push({
            description: item.description,
            money: (item.price * initNum).toFixed(2),
            num: initNum,
            picList: item.picList,
            price: item.price,
            productId: item.productId,
            productName: item.title,
            weight: item.weight
          })
        }
      }
    },
    deleChecked (index) { // 删除已选中的礼品包商品
      this.checkedArr.splice(index, 1)
    },
    getGoodsList (type) { // 获取商品列表
      this.$ajax.post('/api/productSet/getProductListSeller', {
        sortType: this.sortActive.split('-')[1],
        sortField: this.sortActive.split('-')[0],
        limit: this.pageSize,
        currPageNo: this.pageNo,
        canUseAccount: this.userInfo.userName
      }).then((data) => {
        if (data.data.code === '200') {
          let res = data.data.data
          this.goodsDataObj = res
          let arr = []
          for (let i = 0; i < res.datas.length; i++) {
            arr.push({
              description: res.datas[i].description,
              formatDescription: res.datas[i].formatDescription,
              initNum: 1,
              lineThreshold: res.datas[i].lineThreshold,
              picList: res.datas[i].picList,
              price: res.datas[i].price,
              productId: res.datas[i].productId,
              productStatus: res.datas[i].productStatus,
              salesNum: res.datas[i].salesNum,
              statusDetail: res.datas[i].statusDetail,
              stockNum: res.datas[i].stockNum,
              title: res.datas[i].title,
              weight: res.datas[i].weight
            })
          }
          if (type === 'append') { // 分页加载
            this.goodsArr = this.goodsArr.concat(arr)
          } else {
            this.goodsArr = arr
            this.initPackage()
          }
        } else {
          this.$message({
            message: data.data.message,
            type: 'warning'
          })
        }
      }).catch((err) => {
        console.error(err)
        this.$message({
          message: '生意太火爆了, 请稍后再试',
          type: 'error'
        })
      })
    },
    initPackage () { // 初始化一个商品
      if (parseInt(this.type) === 3 && this.goodsArr.length > 0) {
        let item = this.goodsArr[0]
        this.checkedArr = [{
          description: item.description,
          money: (item.price * 1).toFixed(2),
          num: 1,
          picList: item.picList,
          price: item.price,
          productId: item.productId,
          productName: item.title,
          weight: item.weight
        }]
      }
    },
    sureAddPackage (type) { // 确认添加礼品包套餐
      if (this.checkedArr.length === 0) {
        this.$message({
          message: '请选择商品至礼品包',
          type: 'warning'
        })
      } else {
        this.$ajax.post('/api/productSet/addSetTb', {
          sellerAccountId: this.userInfo.sellerAccountId,
          productIds: this.checkedArr
        }).then((data) => {
          if (data.data.code === '200') {
            if (type === 999) {
            } else {
              this.$message({
                message: '添加礼品包成功',
                type: 'success'
              })
            }
            let packages = {
              setId: data.data.data.setId,
              flagCommon: '0',
              productDetail: JSON.stringify(this.checkedArr) + '',
              productPrice: this.totalObj.priceTotal,
              sellerAccountId: this.userInfo.sellerAccountId,
              weight: this.totalObj.weightTotal,
              samPriceTotal: ((this.logisticPrice - 0) + (this.totalObj.priceTotal - 0)).toFixed(2)
            }
            this.setPackages(packages)
            this.$emit('addSuccess')
            if (type === 999) {
              this.$router.push({ name: 'samApplay' })
            }
          } else {
            this.$message({
              message: data.data.message,
              type: 'warning'
            })
          }
        }).catch((err) => {
          console.error(err)
          this.$message({
            message: '生意太火爆了, 请稍后再试',
            type: 'error'
          })
        })
      }
    },
    sureEditPackage () { // 确认编辑礼品包
      if (this.checkedArr.length === 0) {
        this.$message({
          message: '请选择商品至礼品包',
          type: 'warning'
        })
      } else {
        this.$ajax.post('/api/productSet/addSetTb', {
          sellerAccountId: this.userInfo.sellerAccountId,
          productIds: this.checkedArr
        }).then((data) => {
          if (data.data.code === '200') {
            this.$message({
              message: '修改礼品包成功',
              type: 'success'
            })
            let packages = {
              setId: data.data.data.setId,
              flagCommon: '0',
              productDetail: JSON.stringify(this.checkedArr) + '',
              productPrice: this.totalObj.priceTotal,
              sellerAccountId: this.userInfo.sellerAccountId,
              weight: this.totalObj.weightTotal
            }
            this.setPackages(packages)
            this.$emit('editSuccess')
          } else {
            this.$message({
              message: data.data.message,
              type: 'warning'
            })
          }
        }).catch((err) => {
          console.error(err)
          this.$message({
            message: '生意太火爆了, 请稍后再试',
            type: 'error'
          })
        })
      }
    },
    scrollWatch (e) { // 检测商品列表滚动
      this.$nextTick(() => {
        let sH = this.$refs.goodsBox.scrollHeight
        let sT = this.$refs.goodsBox.scrollTop
        let cH = this.$refs.goodsBox.clientHeight
        if ((this.goodsDataObj.currPageNo < this.goodsDataObj.pageNos) && (sH - sT - cH < 20)) {
          this.pageNo = this.pageNo + 1
          this.getGoodsList('append')
        }
      })
    },
    ...mapActions([
      'setPackages'
    ])
  },
  created () {
    this.getGoodsList()
  },
  mounted () {
    this.$refs.goodsBox.addEventListener('mousewheel', this.scrollWatch)
    if (this.fixedArr && this.fixedArr.length > 0) {
      this.checkedArr = this.fixedArr
    }
  }
}
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '../../../assets/stylus/index.styl'
.shopCar
  padding 20px 0 0
  height calc(100% - 20px)
  box-sizing border-box
  display flex
  .tableList
    flex 1
    display flex
    flex-direction column
    .title
      display flex
      justify-content space-around
      fontSize($fontSize, 48px, $fontColor)
      background #F4F4F5
      strong
        position relative
        display inline-flex
        flex-direction column
        align-items center
        vertical-align middle
        cursor pointer
        width 20px
        height 34px
        text-align center
        vertical-align middle
        i
          position absolute
          width 0
          height 0
          border 5px solid transparent
          border-bottom-color #909399
          transition all 0.2s
        .top
          top 5px
        .bottom
          bottom 5px
          transform rotate(180deg)
        .active
          border-bottom-color $mainColor
    .goodsInfo
      flex 1
      overflow auto
      li
        padding 20px 30px
        display flex
        justify-content space-between
        &:nth-child(2n)
          background #F5F7FA
        >div
          align-self center
        .goodsImg
          width 50px
          img
            width 50px
            height 50px
        .goodsDetail
          width 200px
          h6
            fontSize($fontSize, 30px, $fontColor)
          p
            fontSize($fontSize, 20px, $fontColor-gray)
            text-overflow ellipsis
            overflow hidden
            display box
            display -webkit-box
            -webkit-line-clamp 2
            -webkit-box-orient vertical
        .price
          width 100px
          span
            fontSize($fontSize, 28px, $fontColor-gray)
            strong
              color $mainColor
        .operate
          width 150px
          text-align right
          p
            margin-top 12px
      li.loading
        justify-content center
        font-size 20px
        background #ffffff
    ::-webkit-scrollbar
      width 8px
      display block
    ::-webkit-scrollbar-thumb
      border-radius 4px
      background RGBA(136, 136, 136, 0.4)
      &:hover
        background RGBA(136, 136, 136, 1)
  .cars
    width 260px
    padding 20px 12px
    box-sizing border-box
    margin-left 10px
    border 1px solid #DDDDDD
    align-self flex-start
    .titleInput
      h2
        fontSize($fontSize-l, 1, $fontColor)
        text-align center
        font-weight bold
    .checkedList
      margin 20px 0
      max-height 260px
      overflow auto
      li
        margin-bottom 2px
        background #F5F7FA
        padding 8px 12px
        display flex
        justify-content space-between
        align-items center
        img
          width 32px
          height 32px
        span
          fontSize($fontSize-s, 1, $fontColor)
        i
          fontSize($fontSize-m, 1, $fontColor-d)
          cursor pointer
      .noContent
        justify-content center
        img
          width 200px
          height 200px
    ::-webkit-scrollbar
      width 4px
      display block
    ::-webkit-scrollbar-thumb
      border-radius 2px
      background RGBA(136, 136, 136, 0.4)
      &:hover
        background RGBA(136, 136, 136, 1)
    .totalPrice
      padding 0 20px
      span
        fontSize($fontSize, 30px, $fontColor-gray)
        i
          display inline-block
          width 70px
        strong, em
          fontSize($fontSize-m, 30px, $mainColor-gray)
      >b
        fontSize($fontSize-s, 1, $fontColor)
      .total
        fontSize($fontSize-l, 30px, $fontColor)
        >b
          display inline-block
          width 70px
          font-weight bold
          font-size 20px
        strong
          font-size 20px
          color $mainColor
    .footer
      text-align center
      margin 20px 0
      .btns
        margin-top 20px
        display flex
        justify-content center
        b
          white-space nowrap
</style>
